<template>
  <div>
    <div class="department-row">
      <el-input v-model="filterText" :placeholder="$t('index.InsertDepartment')" clearable size="small"
        prefix-icon="el-icon-search" style="width:100%;margin-bottom: 20px" />
    </div>
    <div class="department-row">
      <el-tree ref="tree" style="width:100%;" :data="options" :props="defaultProps" :current-node-key="value"
        :expand-on-click-node="false" :default-expand-all="defaultExpand" :filter-node-method="filterNode" node-key="id"
        highlight-current @node-click="handleNodeClick" />
    </div>
  </div>
</template>

<script>
  import {
    treeselect
  } from '@/api/system/dept'

  export default {
    name: 'DepartmentTree',
    props: {
      value: {
        default: null
      },
      defaultExpand: {
        type: Boolean,
        default: false
      }
    },
    components: {},
    data() {
      return {
        filterText: null,
        options: [],
        defaultProps: {
          children: 'children',
          label: 'label'
        }
      }
    },
    watch: {
      filterText(v) {
        this.$refs.tree.filter(v)
      },
    },
    created() {
      this.queryData()
    },
    methods: {
      queryData() {
        const vm = this
        treeselect().then((response) => {
          vm.options = response.data
          vm.$emit('loaded', response.data)
          vm.$nextTick(vm.setCurrentData)
        })
      },
      setCurrentData() {
        if (!this.value) {
          return
        }
        const data = this.$refs.tree.getCurrentNode(this.value)
        if (!data) {
          return
        }
        this.handleNodeClick(data)
      },
      filterNode(value, data) {
        if (!value) return true
        return data.label.indexOf(value) !== -1
      },
      handleNodeClick(data) {
        this.$emit('input', data.id)
        this.$emit('selected', data)
      },
      clear() {
        this.$refs.tree.setvalue(null)
      }
    }
  }

</script>
<style scoped>
  .department-row {
    width: 100%;
  }

</style>
